const request = require("request");
const querystring = require('querystring');
const server = 'http://www.hush-g-internal.cn';

const Request = {

	get : function(req , path , qs , callback){

		if(typeof qs == "undefined" && typeof callback == "function"){
			qs = {};
		}
		
		if(typeof qs == "function"){
			callback = qs;
			qs = {};
		}

		var headers = {};

		request({
			uri : server + path,
			qs : qs,
			headers : headers,
			method : 'GET'
		},function(error, response, body){
			var data = {};
			try{
				data = JSON.parse(body);
				if(response.statusCode === 200){
					callback(error, response, data);
				}
				else{
					throw data;
				}
				
			}
			catch(err){
				callback(err, response);
			}
			
		});

	},

	post : function(req , path , qs , callback){

		let requestBody = null;
		// 如果req对象不是一个Request对象，那么说明请求是直接在服务内部发起的，那么req直接传递需要
		// post的body
		if( req.hasOwnProperty('method') && req.hasOwnProperty('query') ){
			requestBody = req.body;
		}
		else{
			requestBody = req;
		}

		if(typeof qs == "undefined" && typeof callback == "function"){
			qs = {};
		}
		
		if(typeof qs == "function"){
			callback = qs;
			qs = {};
		}

		var headers = {
			'Content-Type' : 'application/x-www-form-urlencoded'
		};

		request({
			uri : server + path,
			qs : qs,
			headers : headers,
			method : 'POST',
			body : querystring.stringify(requestBody)
		},function(error, response, body){
	
			var data = {};
			try{
				data = JSON.parse(body);
				if(response.statusCode === 200){
					callback(error, response, data);
				}
				else{
					throw data;
				}
				
			}
			catch(err){
				callback(err, response);
			}
		});

	},

	put : function(req , callback){

		request({
			uri : server + req.url,
			method : 'PUT',
			body : JSON.stringify(req.body)
		},function(error, response, body){
			var data = {};
			try{
				data = JSON.parse(body);
				if(response.statusCode === 200){
					callback(error, response, data);
				}
				else{
					throw data;
				}
				
			}
			catch(err){
				callback(err, response);
			}
		});

	},

	delete : function(req , callback){

		request({
			uri : server + req.url,
			method : 'DELETE'
		},function(error, response, body){
			var data = {};
			try{
				data = JSON.parse(body);
				if(response.statusCode === 200){
					callback(error, response, data);
				}
				else{
					throw data;
				}
				
			}
			catch(err){
				callback(err, response);
			}
		});

	}

};

module.exports = Request;